package com.zh.chat.controller;

import org.apache.log4j.Logger;

import com.zh.chat.dao.FriendsDAO;
import com.zh.chat.dao.UserDAO;
import com.zh.chat.entity.UDPProtocol;
import com.zh.chat.service.impl.NetServiceImpl;

/**
 * 服务器运行环境
 * 
 * @author tom
 */
public class ServerController {
	private Logger log = Logger.getLogger(ServerController.class);
	private static ServerController controller = null;
	
	public static ServerController getInstance(){
		if(controller==null){
			controller = new ServerController();
		}
		return controller;
	}
	private ServerController(){}
	
	private NetServiceImpl netService = null;
	private UserDAO userDao = null;
	private FriendsDAO friendsService = null;
	
	public UserDAO getUserService() {
		return userDao;
	}


	public void setUserService(UserDAO userService) {
		this.userDao = userService;
		log.info("ServerContorller加载UserService完成");
	}

	public FriendsDAO getFriendsService() {
		return friendsService;
	}


	public void setFriendsService(FriendsDAO friendsService) {
		this.friendsService = friendsService;
		log.info("ServerContorller加载FriendsService完成");
	}


	public NetServiceImpl getNetService() {
		return netService;
	}
	/**
	 * 加载控制器网络服务
	 * @param netDTO
	 */
	public void setNetService(NetServiceImpl netService) {
		this.netService = netService;
		log.info("ServerContorller加载NetService完成");
	}

	public void start() {
		AcceptThread accepts = new AcceptThread(controller);
		Thread listenThread = new Thread(accepts);
		try{
			listenThread.start();
			System.out.println("开始监听");
		}catch(NullPointerException e){
			e.printStackTrace();
		}
	}

}
class AcceptThread implements Runnable{
	boolean running = false;
	private UDPProtocol protocol = null;
	ServerController controller = null;
	
	public AcceptThread(ServerController controller) {
		running = true;// 标记服务器开始运行
		this.controller = controller;
	}
	
	public void setRunning(boolean running) {
		this.running = running;
	}
	
	@Override
	public void run() {
		while (running) {
			protocol = controller.getNetService().recive();
			if (protocol != null) {
				Thread userThread = new Thread(new AnalyzeThread(protocol, controller));
				userThread.start();
			}
		}
	}
}